<!--
 * @Author: Nico
-->
<template>
  <UiPdaFormItem :class="{ hidden: info.extension.hidden.value || conditionProperty.hidden }" :info="info">
    <van-field
      :ref="info._id"
      v-model.trim="formDataModelLabel"
      v-ui-ref="vSetRef"
      class="border-b-2 rounded-none uiPdaSelect"
      :class="{ hasPrefix: info.extension.prefixIcon && info.extension.prefixIcon.value }"
      :disabled="info.extension.disabled.value || conditionProperty.disabled"
      :label="info.extension.label.value"
      :name="info.extension.model.value"
      :placeholder="translateTitle('Ve.elements.请选择')"
      readonly
      :required="info.extension.extendRule.value.required && info.extension.extendRule.value.ChangeSwitch"
      :right-icon="info.extension?.isClear?.value ? 'close' : 'none'"
      type="text"
      @click="clickItem"
      @click-right-icon.stop="clickRightIcon()"
    />
    <van-popup position="bottom" :show="showPicker">
      <!-- {{ info.extension.labelField.value }} -->
      <!-- {{ '请选择' + info.extension.LOT_SEQ_NAME_PDA }} -->
      <van-picker
        :columns="optionList"
        :columns-field-names="{ text: info.extension.labelField.value, value: info.extension.valueField.value }"
        :default-index="0"
        :title="'请选择' + info.extension.label.value"
        @cancel="showPicker = false"
        @confirm="selConfirm($event)"
      />
    </van-popup>
  </UiPdaFormItem>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import { Field, Popup, Picker } from 'vant'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isEmpty from 'lodash/isEmpty'
  import merge from 'lodash/merge'
  import trim from 'lodash/trim'
  import isArray from 'lodash/isArray'
  // import cloneDeep from 'lodash/cloneDeep'
  // import { customAlphabet } from 'nanoid'
  import { defineComponent } from 'vue'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin } from '@ve/mixin'

  export default defineComponent({
    name: 'UiPdaSelect',
    components: {
      [Field.name]: Field,
      [Popup.name]: Popup,
      [Picker.name]: Picker,
    },
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin],
    data() {
      return {
        showPicker: false,
        formDataModelLabel: '',
        optionList: [],
        getOutKey: [],
        conditionProperty: {
          disabled: false,
          hidden: false,
        },
      }
    },
    computed: {
      optionConfigData() {
        return this.info.extension.optionConfig.value
      },
    },
    watch: {
      // 下拉选的数据
      optionConfigData: {
        handler(newVal) {
          this.optionList = newVal
          this.showModel()
        },
      },
    },
    created() {
      // 预览时候显示初始化数据
      this.optionList = this.info.extension.optionConfig.value
      this.showModel()
    },
    mounted() {
      // 判断是否有配置获取选项
      if (this.hasPreview && this.info.extension.api.value) {
        // 如果配置了默认不请求 则取消请求
        if (this.info.extension.dontRequest && this.info.extension.dontRequest.value) return
        this.requestOptionList()
      }
    },

    methods: {
      translateTitle,
      showModel() {
        //  显示输入框得下拉值
        if (!isEmpty(this.info.extension.optionConfig.value)) {
          let chaceItem = this.info.extension.optionConfig.value.find((v) => {
            return v[this.info.extension.valueField.value] == this.formDataModel
          })
          if (isEmpty(chaceItem)) {
            return
          }
          this.formDataModelLabel = processingConstant(this, chaceItem[this.info.extension.labelField.value])

          this.putSelect(chaceItem)
        }
      },
      requestOptionList() {
        let requestDataObj = {}
        isArray(this.info.extension.requestData.value) &&
          this.info.extension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.info.data.formData)
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
        let options = {
          api: this.info.extension.api.value,
          method: this.info.extension.method.value,
          getDataKey: this.info.extension.getDataKey.value,
          data: merge(requestDataObj, this.info.data.formData),
        }
        if (!trim(options.api)) return
        this.request(options)
      },
      // 请求接口
      request(options = {}) {
        this.loading = true
        let getDataKey = options.getDataKey
        //发起请求

        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          this.loading = false
          this.optionList = isEmpty(getDataKey) ? res.data.data || [] : res.data[getDataKey].data || []

          if (this.info.extension?.isDefault?.value?.key && this.info.extension?.isDefault?.value?.value) {
            let item = this.optionList.filter((el) => el[this.info.extension?.isDefault?.value?.key] == this.info.extension?.isDefault?.value?.value)
            if (this.info.extension.isDefault.value && item && item.length > 0) {
              if (item.length > 1 && this.info.extension?.multiple?.value) {
                this.formDataModel = item.map((el) => el[this.info.extension.valueField.value])
              } else {
                this.formDataModel = item[0][this.info.extension.valueField.value]
              }
            }
          }
          this.info.extension.optionConfig.value = this.optionList
        })
      },
      //下拉选的确定按钮
      selConfirm(event) {
        if (!isEmpty(event)) {
          this.formDataModelLabel = event[this.info.extension.labelField.value] //下拉选显示字段
          this.formDataModel = event[this.info.extension.valueField.value] //绑定form表单字段

          this.putSelect(event)
          this.runEventTask('checked')
          this.cursorHover()
        }
        this.showPicker = false
      },
      // 放置表单下拉选中文
      putSelect(event) {
        // 1. 先查找到当前组件所在得表单组件
        // this里面有一个 formId 属性存储了当前组件所在的表单组件的 id，直接取来用即可
        // 通过 formId 在 vuiComponents 中找到表单组件的实例
        const formSelf = this.vuiComponents[this.formId] && this.vuiComponents[this.formId].self
        // 2. 在表单组件中获取LOT01 ~ LOT48的值，然后返回
        if (!formSelf) return {}

        // 在表单实例中拿到表单的值
        let fromData = formSelf.info.data.formData
        //给表单防止下拉选中文
        fromData[this.info.extension.model.value + 'CODE'] = this.formDataModelLabel
        //给表单放置下拉选扩展字段
        // fromData[this.info.extension.getOutKey.value] = this.getOutKey
        let arr = []
        this.getOutKey = []

        if (this.info.extension?.getOutKey?.value && !isEmpty(event)) {
          arr = this.info.extension?.getOutKey?.value.split(',')
          if (!isEmpty(arr)) {
            arr.forEach((v) => {
              if (event[v]) {
                this.getOutKey.push({
                  [v]: event[v],
                })
              }
            })
          }

          this.getOutKey.forEach((v) => {
            fromData[Object.keys(v)[0]] = Object.values(v)[0]
          })
        } //绑定的扩展字段
      },
      // 点击输入框
      clickItem() {
        if (!this.hasPreview) {
          return
        }
        if (this.info.extension.disabled.value || this.conditionProperty.disabled) {
          console.log('不许弹出来！你被禁用了！！！哈哈哈')
        } else {
          this.showPicker = true
        }
      },
      $closeModel() {
        this.showPicker = true
      },
      clickRightIcon() {
        this.formDataModelLabel = ''
        this.formDataModel = ''
      },
    },
  })
</script>
<style lang="scss" scoped>
  .uiPdaSelect {
    :deep() .hasPrefix .el-input__inner {
      padding-left: 25px;
    }
    .van-cell {
      flex-wrap: wrap !important;
      padding: 0rem !important;
      display: flex !important;
    }
    :deep() .van-field__value {
      overflow: visible;
      width: 100%;
      flex: none !important;
    }
    :deep() .van-field__control {
      text-indent: 10px !important;
      font-size: 0.8rem !important;
    }

    :deep() .van-icon-search {
      color: rgb(42, 119, 182);
      font-size: 1rem !important;
    }
    :deep() .van-field__label--center {
      font-size: 0.8rem !important;
      padding: 0.5rem 0rem;
    }
    :deep() .van-cell__title {
      font-size: 0.8rem !important;
    }
    :deep() .van-field__left-icon {
      margin: 0rem !important;
      width: 0.8rem !important;
    }
    // :deep() .van-field__label {
    //   width: 70%;
    // }
  }
</style>
